package com.funeral.diyaccount.common.page.util;

import com.funeral.diyaccount.common.page.pojo.PageObject;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsDateJsonBeanProcessor;
import net.sf.json.util.CycleDetectionStrategy;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by peizangpin on 2017/5/5.
 */
public class PageUtils {

    public static PageObject initPageObject(PageObject pageObject,Integer defaultRows){
        if(pageObject == null){
            pageObject = new PageObject();
        }
        pageObject.setDefaultRows(defaultRows);
        pageObject.setPage(1);
        pageObject.setTotal(0);
        pageObject.setRowsList(null);
        pageObject.setRows(defaultRows);
        return pageObject;
    }

    public static PageObject initPageObject(HttpServletRequest request){
        PageObject pageObject = new PageObject();
        pageObject = PageUtils.initPageObject(pageObject,20);
        if(request != null){
            String rowsStr = request.getParameter("rows");
            String pageStr = request.getParameter("page");
            if(StringUtils.isNotBlank(rowsStr) && StringUtils.isNumeric(rowsStr) ){
                pageObject.setRows(Integer.valueOf(rowsStr));
            }
            if(StringUtils.isNotBlank(pageStr) && StringUtils.isNumeric(pageStr) ){
                pageObject.setPage(Integer.valueOf(pageStr));
            }
        }

        return pageObject;
    }

    public static JSONObject ToEasyUIDatagridJSON(PageObject pageObject){
        JSONObject result = new JSONObject();
        result.put("rows",pageObject.getRowsList());
        result.put("total",pageObject.getTotal());
        return  result;
    }

    public static JSONObject ToEasyUIDatagridJSON(PageObject pageObject,JsonConfig jsonConfig){
        JSONObject result = new JSONObject();
        JSONArray jsonArr = JSONArray.fromObject(pageObject.getRowsList(),jsonConfig);
        result.put("rows",jsonArr);
        result.put("total",pageObject.getTotal());
        return  result;
    }


}